package org.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
class gai {
    public static void main(String[] args) throws Exception {
        System.out.println("保存用户：");
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_maven?useUnicode=true&characterEncoding=utf8",
                "root", "");

        // 保存数据
        String usrename = "麓山";
        int age = 50;
        Date birth = new Date();

        String sql = "insert into user(usrename,age,birthy) values(?,?,?)";
        // 预编译sql语句
        PreparedStatement pstmt = conn.prepareStatement(sql);
        // 给占位符赋值
        pstmt.setString(1, usrename);
        pstmt.setInt(2, age);
        pstmt.setObject(3, birth);
        // 执行sql
        pstmt.executeUpdate();// delete update insert
        // 如果保存到额数据中文有乱码 创建数据库的时候没有指定 编码格式


        // 准备pstmt对象
        pstmt = conn.prepareStatement("select * from user ");

        // 执行sql语句
        ResultSet rs = pstmt.executeQuery();

        // 循环获取数据

        while (rs.next()) {
            System.out.print(rs.getInt("id") + "\t");
            System.out.print(rs.getString("usrename") + "\t");
            System.out.print(rs.getInt("age") + "\t");
            System.out.print(rs.getTimestamp("birthy") + "\t");
            System.out.println();
        }

        rs.close();
        conn.close();

    }
}